package com.websocket.demo.controller;

import com.websocket.demo.entity.Message;
import com.websocket.demo.interceptor.SessionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.time.LocalDateTime;

/**
 * @Author hezhan
 * @Date 2019/9/24 17:28
 */
@RestController
public class StompController {

    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    @Autowired
    SessionHandler sessionHandler;

    @MessageMapping("/message")
    public void subscription(Message message, Principal principal) throws Exception {
        simpMessagingTemplate.convertAndSendToUser(message.getTo(), "/queue", new Message(message.getMessage(), message.getDatetime(), message.getFrom(), message.getTo()));
        System.out.println(principal.getName() + "发送了一条消息给：" + message.getTo());
    }



    //广播推送消息
    @Scheduled(fixedRate = 10000)
    public void sendTopicMessage() {
        Message user=new Message();
        user.setFrom("后台广播");
        user.setMessage("后台广播消息测试");
        user.setDatetime(LocalDateTime.now().toString());
        System.out.println("开始广播: " + user.toString());
        simpMessagingTemplate.convertAndSend("/topic/getResponse",user);
    }

    //客户端主动发送消息到服务端，服务端马上回应指定的客户端消息
    //类似http无状态请求，但是有质的区别
    //websocket可以从服务器指定发送哪个客户端，而不像http只能响应请求端

    //群发
    @MessageMapping("/massRequest")
    //SendTo 发送至 Broker 下的指定订阅路径
    @SendTo("/mass/getResponse")
    public Message mass(Message chatRoomRequest){
        //方法用于群发测试
        System.out.println("name = " + chatRoomRequest.getFrom());
        System.out.println("chatValue = " + chatRoomRequest.getMessage());
        return chatRoomRequest;
    }

    //单独聊天
    @MessageMapping("/aloneRequest")
    public Message alone(Message message, Principal principal){
        //方法用于一对一测试
        simpMessagingTemplate.convertAndSendToUser(message.getTo(), "/queue", new Message(message.getMessage(), message.getDatetime(), message.getFrom(), message.getTo()));
        System.out.println(principal.getName() + "发送了一条消息给：" + message.getTo());
//        this.template.convertAndSendToUser(chatRoomRequest.getUserId()+"","/alone/getResponse",response);
        return message;
    }

}
